<template>
  <div>
    <div class="receipt-order-edit-wrapper app-container" style="margin-bottom: 60px" v-loading="loading">
      <el-card header="订单基本信息">
        <el-form label-width="108px" :model="form" ref="receiptForm" :rules="rules">
          <el-row :gutter="24">
            <el-col :span="11">
              <el-form-item label="订单单号" prop="order_id">
                <el-input class="w200" v-model="form.order_id" placeholder="订单单号" :disabled="form.id"></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="仓库" prop="warehouseId">
                <el-select v-model="form.warehouseId" placeholder="请选择仓库" filterable>
                  <el-option v-for="item in useWmsStore().warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="6">
              <el-form-item label="总数量" prop="totalQuantity">
                <el-input-number style="width:100%" v-model="form.totalQuantity" :controls="false" :precision="0" :disabled="true"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="11">
              <el-form-item label="订单类型" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio-button
                    v-for="item in wms_shipment_status"
                    :key="item.value"
                    :label="item.value">
                    {{ item.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="供应商" prop="merchantId">
                <el-select v-model="form.merchantId" placeholder="请选择供应商" clearable filterable>
                  <el-option v-for="item in useWmsStore().merchantList" :key="item.id" :label="item.merchantName" :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="6">
              <el-form-item label="客户名称" prop="customer">
                <el-input v-model="form.customer" placeholder="请输入客户名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="11">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-model="form.remarks"
                  placeholder="备注...100个字符以内"
                  rows="4"
                  maxlength="100"
                  type="textarea"
                  show-word-limit="show-word-limit"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div style="display: flex;align-items: start">
                <el-form-item label="下单日期" prop="order_date">
                  <el-input type="date" v-model="form.order_date"/>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card header="订单明细" class="mt10">
        <div class="receipt-order-content">
          <div class="flex-space-between mb8">
            <el-popover
              placement="left"
              title="提示"
              :width="200"
              trigger="hover"
              :disabled="form.order_id"
              content="请先输入订单单号！"
            >
              <template #reference>
                <el-button type="primary" plain="plain" size="default" @click="showAddItem" icon="Plus" :disabled="!form.order_id">添加订单</el-button>
              </template>
            </el-popover>
          </div>
          <el-table :data="form.detail" border empty-text="暂无订单明细">
            <el-table-column label="产品ID">
              <template #default="{ row }">
                <div>{{ row.product_id }}</div>
              </template>
            </el-table-column>


            <el-table-column label="产品名称">
              <template #default="{ row }">
                <el-select v-model="row.product_id" @change="checkProductOptionList()">
                  <el-option v-for="option in optionList" :value="option.id" :key="option.id" :label="option.text" :disabled="optionListChecker.includes(option.id)">
                    {{ option.text }}
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="数量" prop="quantity">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.quantity"
                  placeholder="数量"
                  :min="1"
                  :precision="0"
                  @change="handleChangeQuantity"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="right" fixed="right">
              <template #default="scope">
                <el-button icon="Delete" type="danger" plain size="small" @click="handleDeleteDetail(scope.row, scope.$index)" link>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
    <div class="footer-global">
      <div class="btn-box">
        <div>
          <el-button @click="doWarehousing" type="primary" class="ml10">完成订单</el-button>
        </div>
        <div>
          <el-button @click="cancel" class="mr10">取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="ReceiptOrderEdit">
import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {ElMessage} from "element-plus";
import {useRoute} from "vue-router";
import {generateNo } from '@/api/wms-order/NewOrderId'
// import {delReceiptOrderDetail } from '@/api/wms/receiptOrderDetail'
import {getorderdata, UpdateOrder, CreateOrder} from "@/api/wms-order/product"
import {ProductList} from "@/api/wms-django/product/product"

const {proxy} = getCurrentInstance();

const wms_shipment_status = ref([
  {
    label: '未审核',
    value: '-1'
  },
  {
    label: '未出库',
    value: '0'
  },
  // {
  //   label: '已出库',
  //   value: '1'
  // },
  // {
  //   label: '作废',
  //   value: '2'
  // },
  // {
  //   label: '驳回',
  //   value: '3'
  // }
])
const optionListChecker = ref([])
const selectedSku = ref([])
const loading = ref(false)
const NewData = ref(false)
const initFormData = {
  order_id: undefined,
  status: "-1",
  // merchantId: undefined,
  customer: undefined,
  order_date: undefined,
  orderStatus: 0,
  remarks: undefined,
  // warehouseId: undefined,
  totalQuantity: 0,//总数量
  detail: [],
}

const templateRow = {
  detail_id: undefined,
  order_id: undefined,
  product_id: undefined,
  product_name: undefined,
  quantity: undefined
}

const data = reactive({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    order_id: undefined,
    status: undefined,
    customer: undefined,
    remarks: undefined,
    order_date: undefined,
    orderStatus: undefined,
  },
  rules: {
    order_id: [
      {required: true, message: "订单单号不能为空", trigger: "blur"}
    ],
    // warehouseId: [
    //   {required: true, message: "请选择仓库", trigger: ['blur', 'change']}
    // ]
  }
});
const { form, rules} = toRefs(data);

const cancel = async () => {
  await proxy?.$modal.confirm('确认取消编辑订单吗？');
  close()
}
const close = () => {
  const obj = {path: "/OrderBy"};
  proxy?.$tab.closeOpenPage(obj);
}

// 选择订单 start
const showAddItem = () => {
  //skuSelectRef.value.getList()
  //skuSelectShow.value = true
  form.value.detail.push({...templateRow});
}

// 初始化receipt-order-form ref
const receiptForm = ref()

const getParamsBeforeSave = () => {
  let Returndetails = []
  let Inputname
  form.value.detail.product_name = optionList.value.product_name
  if (form.value.detail?.length) {
    Returndetails = form.value.detail.map(it => {
      for(let i = 0; i < optionList.value.length; i++){
        if(optionList.value[i].id === it.product_id){
          Inputname = optionList.value[i].text
        }
      }
      const base = {
        product_id: it.product_id,
        product_name: Inputname,
        // order_id: it.order_id,
        quantity: it.quantity,
        // warehouseId: form.value.warehouseId,
      }
      return it.detail_id ? { ...base, detail_id: it.detail_id } : base
    })
  }

  return {
    order_id: form.value.order_id,
    status: form.value.status,
    // merchantId: form.value.merchantId,
    customer: form.value.customer,
    remarks: form.value.remarks,
    order_date: form.value.order_date,
    totalQuantity: form.value.totalQuantity,
    // warehouseId: form.value.warehouseId,
    detail: Returndetails
  }
}


const checkProductOptionList = () => {
  optionListChecker.value = []
  form.value.detail.forEach(row => {
    optionList.value.forEach(element => {
      if (element.id === row.product_id) {
          optionListChecker.value.push(element.id)
      }
    });
  });
}

const doWarehousing = async () => {
  await proxy?.$modal.confirm('确认添加订单吗？');
  receiptForm.value?.validate((valid) => {
    // 校验
    if (!valid) {
      return ElMessage.error('请填写必填项')
    }
    const params = getParamsBeforeSave();

    loading.value = true
    if(NewData.value){
      CreateOrder(params).then((res) => {
        if (res.status === 201) {
          ElMessage.success('订单添加成功')
          close()
        } else {
          ElMessage.error(res.msg)
        }
        }).finally(() => {
          loading.value = false
        })
      } else {
      UpdateOrder(params.order_id ,params).then((res) => {
        if (res.status === 200) {
          ElMessage.success('订单修改成功')
          close()
        } else {
          ElMessage.error(res.msg)
        }
        }).finally(() => {
          loading.value = false
        })
    }
  })
}

const route = useRoute();
onMounted(() => {
  const id = route.query && route.query.id;
  if (id) {
    loadDetail(id)
  } else {
    form.value.order_id = generateNo()
    NewData.value = true
  }
})

// 获取订单详情
const loadDetail = (query) => {
  loading.value = true
  getorderdata(query).then((response) => {
    form.value = {...response.data}
    if (response.data.detail?.length) {
      selectedSku.value = response.data.detail.map(it => {
        return {
          id: it.skuId
        }
      })
    }
    Promise.resolve();
  }).then(() => {
  }).finally(() => {
    loading.value = false
    let sum = 0
    for(let i = 0 ; i<form.value.detail.length ; i++){
      sum += Number(form.value.detail[i].quantity)
    }
    form.value.totalQuantity = sum

  })
}

const handleChangeQuantity = () => {
  let sum = 0
  form.value.detail.forEach(it => {
    if (it.quantity) {
      sum += Number(it.quantity)
    }
  })
  form.value.totalQuantity = sum
}

// 画面删除
const handleDeleteDetail = (row, index) => {
  form.value.detail.splice(index, 1)
  const indexOfSelected = selectedSku.value.findIndex(it => row.product_id=== it.product_id)
  selectedSku.value.splice(indexOfSelected, 1)
}

// 获取产品信息
const optionList = ref([]);

const GetoptionList = () =>{
  ProductList().then(
    res => {
      res.data.forEach(element => {
        optionList.value.push({
          id: element.product_id,
          text: element.product_name
        })
      })
    }
  )
}

watch([form, optionList], () => {
  checkProductOptionList()
}, {
  deep: true
})

GetoptionList()


</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.module";

.btn-box {
  width: calc(100% - #{$base-sidebar-width});
  display: flex;
  align-items: center;
  justify-content: space-between;
  float: right;
}
</style>
